<?php

namespace app\admin\controller\auth;

use app\admin\controller\Base;
use app\common\model\auth\AuthRoleModel;
use app\common\model\auth\AuthAdminModel;

class Admin extends Base
{
    /**
     * 管理员列表
     */
    public function list()
    {
        $params = request()->only(['page', 'limit', 'field_type', 'field_value', 'status', 'role_ids']);
        if (isset($params['field_type']) && !empty($params['field_type']) && isset($params['field_value']) && !empty($params['field_value'])) {
            $where[] = [$params['field_type'], 'like', "%{$params['field_value']}%"];
        }

        $sqlObj = (new AuthAdminModel)->where($where ?? [])
            ->field('id,name,role_ids,sex,email,head_img,mobile,status,login_ip,birthday,login_num,login_time,create_time');
        if (isset($params['role_ids']) && !empty($params['role_ids'])) {
            $sqlObj->where("concat(',', role_ids , ',') regexp concat(',',replace('{$params['role_ids']}',',',',|,'),',')");
        }
        if (isset($params['status']) && !empty($params['status'])) {
            $sqlObj->whereIn('status', explode(',', $params['status']));
        }

        $list = $sqlObj->paginate([
            'list_rows' => $params['limit'] ?? 10,
            'page' => $params['page'] ?? 1
        ]);
        foreach ($list->items() as &$v) {
            $v['status_attr'] = (new AuthAdminModel)->status[$v['status']];
            $v['role_names'] = (new AuthRoleModel)->getNamesByIds($v['role_ids']);
            $v['sex_attr'] = (new AuthAdminModel)->sex[$v['sex']];
            $v['url'] = get_file_url($v['head_img']);
        }

        return response_success('', [
            'count' => $list->total(),
            'data' => $list->items()
        ]);
    }

    /**
     * 添加管理员
     */
    public function add()
    {
        $params = request()->only(['name', 'mobile', 'role_ids', 'sex', 'email', 'head_img', 'status', 'password', 'birthday', 'confirm_password']);
        $this->validate($params, [
            'name|名称' => 'require',
            'mobile|手机号' => 'mobile',
            'role_ids' => 'require',
            'status|状态' => 'require|in:1,2',
            'sex|性别' => 'require|in:1,2',
            'password|密码' => 'require',
            'birthday|生日' => 'date',
            'confirm_password|确认密码' => 'require'
        ], [
            'role_ids.require' => '请选择所属角色',
        ]);

        if ((new AuthAdminModel)->where('name', $params['name'])->find()) {
            return response_error('角色名称已存在');
        }
        if ((new AuthAdminModel)->where('mobile', $params['mobile'])->find()) {
            return response_error('手机号已被注册');
        }
        if ($params['password'] != $params['confirm_password']) {
            return response_error('两次密码输入不一致');
        }

        if (isset($params['birthday']) && empty($params['birthday'])) {
            unset($params['birthday']);
        }

        $params['password'] = (new AuthAdminModel)->createPassword($params['password']);
        $params['create_time'] = date('Y-m-d H:i:s');
        unset($params['confirm_password']);
        (new AuthAdminModel)->insert($params);

        return response_success();
    }

    /**
     * 编辑管理员
     */
    public function edit()
    {
        $params = request()->only(['id', 'name', 'mobile', 'role_ids', 'sex', 'email', 'head_img', 'status', 'password', 'birthday', 'confirm_password']);
        $this->validate($params, [
            'id|ID' => 'require',
            'name|名称' => 'require',
            'mobile|手机号' => 'mobile',
            'role_ids' => 'require',
            'status|状态' => 'require|in:1,2',
            'sex|性别' => 'require|in:1,2',
            'birthday|生日' => 'date',
        ], [
            'role_ids.require' => '请选择所属角色',
        ]);

        $adminInfo = (new AuthAdminModel)->where('id', $params['id'])->findOrEmpty()->toArray();
        if (!$adminInfo) {
            return response_error('管理员信息不存在或已删除');
        }

        if ((new AuthAdminModel)->where('id', '<>', $adminInfo['id'])->where('name', $params['name'])->find()) {
            return response_error('账号名称已存在');
        }
        if ((new AuthAdminModel)->where('id', '<>', $adminInfo['id'])->where('mobile', $params['mobile'])->find()) {
            return response_error('手机号已被注册');
        }
        if (isset($params['password']) && isset($params['confirm_password']) && !empty($params['password']) && !empty($params['confirm_password'])) {
            if ($params['password'] != $params['confirm_password']) {
                return response_error('两次密码输入不一致');
            }

            $params['password'] = (new AuthAdminModel)->createPassword($params['password']);
            unset($params['confirm_password']);
        } else {
            if (isset($params['password'])) {
                unset($params['password']);
            }
            if (isset($params['confirm_password'])) {
                unset($params['confirm_password']);
            }
        }

        if ($this->adminInfo['is_admin'] == AuthAdminModel::IS_ADMIN_NO && $adminInfo['id'] != $this->adminInfo['id']) {
            return response_error('非Root权限，仅限操作自己账户');
        }

        if (isset($params['birthday']) && empty($params['birthday'])) {
            unset($params['birthday']);
        }

        $params['update_time'] = date('Y-m-d H:i:s');
        (new AuthAdminModel)->where('id', $adminInfo['id'])->update($params);

        return response_success();
    }

    /**
     * 修改资料（编辑阉割版-仅修改基础信息）
     */
    public function editInfo()
    {
        $params = request()->only(['id', 'name', 'mobile', 'sex', 'email', 'head_img', 'password', 'birthday', 'confirm_password']);
        $this->validate($params, [
            'id|ID' => 'require',
            'name|名称' => 'require',
            'mobile|手机号' => 'mobile',
            'sex|性别' => 'require|in:1,2',
            'birthday|生日' => 'date'
        ]);

        if ($this->adminInfo['id'] != $params['id']) {
            return response_error('仅限修改个人资料');
        }

        $adminInfo = (new AuthAdminModel)->where('id', $params['id'])->findOrEmpty()->toArray();
        if (!$adminInfo) {
            return response_error('管理员信息不存在或已删除');
        }

        if ((new AuthAdminModel)->where('id', '<>', $adminInfo['id'])->where('name', $params['name'])->find()) {
            return response_error('账号名称已存在');
        }
        if ((new AuthAdminModel)->where('id', '<>', $adminInfo['id'])->where('mobile', $params['mobile'])->find()) {
            return response_error('手机号已被注册');
        }
        if (isset($params['password']) && isset($params['confirm_password']) && !empty($params['password']) && !empty($params['confirm_password'])) {
            if ($params['password'] != $params['confirm_password']) {
                return response_error('两次密码输入不一致');
            }

            $params['password'] = (new AuthAdminModel)->createPassword($params['password']);
            unset($params['confirm_password']);
        } else {
            if (isset($params['password'])) {
                unset($params['password']);
            }
            if (isset($params['confirm_password'])) {
                unset($params['confirm_password']);
            }
        }

        if (isset($params['birthday']) && empty($params['birthday'])) {
            unset($params['birthday']);
        }

        $params['update_time'] = date('Y-m-d H:i:s');
        (new AuthAdminModel)->where('id', $adminInfo['id'])->update($params);

        return response_success();
    }

    /**
     * 冻结|恢复管理员账户
     */
    public function changeStatus()
    {
        $params = request()->only(['id']);
        $this->validate($params, [
            'id|ID' => 'require'
        ]);

        $adminInfo = (new AuthAdminModel)->where('id', $params['id'])->findOrEmpty()->toArray();
        if (!$adminInfo) {
            return response_error('管理员信息不存在或已删除');
        }

        if ($this->adminInfo['is_admin'] == AuthAdminModel::IS_ADMIN_NO && $adminInfo['id'] != $this->adminInfo['id']) {
            return response_error('非Root权限，仅限操作自己账户');
        }

        (new AuthAdminModel)->where('id', $adminInfo['id'])->update([
            'status' => $adminInfo['status'] == AuthAdminModel::STATUS_NORMAL ? AuthAdminModel::STATUS_FREEZE : AuthAdminModel::STATUS_NORMAL,
            'update_time' => date('Y-m-d H:i:s')
        ]);

        return response_success();
    }

    /**
     * 获取管理员信息
     */
    public function getInfo()
    {
        $params = request()->only(['id']);
        $this->validate($params, [
            'id|ID' => 'require'
        ]);

        $adminInfo = (new AuthAdminModel)->where('id', $params['id'])
            ->field('id,name,mobile,email,head_img,sex,status,role_ids,birthday')
            ->findOrEmpty()->toArray();
        if (!$adminInfo) {
            return response_error('管理员信息不存在或已删除');
        }

        $adminInfo['url'] = get_file_url($adminInfo['head_img']);
        return response_success('', $adminInfo);
    }

}